// components/wxpay-apply-form/index.js
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { WXPAYMENT_ORGANIZATION_TYPE_VALUE, WXPAYMENT_CONTACT_TYPE_VALUE } from '../../../constants/payment';
import { chooseImage, getImageInfo, readFile, tipToast, copyText } from '../../../common/env';
import { isValidPhone, isValidMail, formatDate } from '../../../common/utils';
import { uploadWxpayApplyMedia } from '../../../api/brd';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        formInfo: {
            type: Object,
            value: {},
        },
    },
    observers: {
        'formInfo': function (val) {
            if (val && val.qualificationsUrl) {
                let qualificationsUrl = val.qualificationsUrl.map(url => {
                    return { url };
                });
                this.setData({ qualificationsUrl });
            }
        },
    },
    data: {
        WXPAYMENT_ORGANIZATION_TYPE_VALUE,
        WXPAYMENT_CONTACT_TYPE_VALUE,
        idCardValidTimePopup: {
            show: false,
            columns: [
                { value: '非长期', name: '非长期' },
                { value: '长期', name: '长期' },
            ],
        },
        idCardValidTimeDatePopup: {
            show: false,
            minDate: new Date(new Date().getFullYear(), 0, 1).getTime(),
            maxDate: new Date(new Date().getFullYear() + 100, 11, 31).getTime(),
        },
        qualificationsUrl: [],
        ocrFlag: {
            idCardCopy: false,
            idCardNational: false,
            businessLicenseCopy: false,
        },
    },
    methods: {
        handleCopy() {
            copyText('https://kf.qq.com/faq/190610B7baQb190610NN3mQN.html', () => {
                tipToast('复制成功，请浏览器打开，查看特殊资质');
            });
        },
        async _handleUploadMedia(e, fileUrl) {
            const { formInfo } = this.data;
            const { name, subName, urlName } = e.currentTarget.dataset;
            if (!fileUrl) {
                fileUrl = (await chooseImage({ sizeType: ['compressed'] }))[0];
            }
            const fileInfo = await getImageInfo(fileUrl);
            if (['jpg', 'jpeg', 'png'].indexOf(fileInfo.type) === -1) {
                tipToast('图片格式仅支持jpg、png');
            } else {
                const base64 = await readFile(fileUrl);
                const res = await uploadWxpayApplyMedia({ image: base64.data, imageType: fileInfo.type === 'jpeg' ? 'jpg' : fileInfo.type });
                if (res) {
                    if (name === 'qualifications') {
                        formInfo.qualifications = formInfo.qualifications || [];
                        formInfo.qualificationsUrl = formInfo.qualificationsUrl || [];
                        formInfo.qualifications.push(res.mediaId);
                        formInfo.qualificationsUrl.push(fileUrl);
                    } else {
                        formInfo[name] = formInfo[name] || {};
                        formInfo[name][subName] = res.mediaId;
                        formInfo[name][urlName] = fileUrl;
                    }
                    this.setData({ formInfo });
                }
            }
        },
        handleOcrSuccess(e) {
            const { formInfo } = this.data;
            const { image_path } = e.detail;
            const { subName } = e.currentTarget.dataset;
            if (subName === 'idCardCopy') {
                const { id = {}, name = {} } = e.detail;
                formInfo.idCardInfo = formInfo.idCardInfo || {};
                formInfo.idCardInfo.idCardName = name.text || formInfo.idCardInfo.idCardName || '';
                formInfo.idCardInfo.idCardNumber = id.text || formInfo.idCardInfo.idCardNumber || '';
                !image_path && this.setData({
                    'ocrFlag.idCardCopy': false,
                });
            } else if (subName === 'idCardNational') {
                const { valid_date = {} } = e.detail;
                if (valid_date.text) {
                    const arr = valid_date.text.split('-');
                    let text;
                    if (arr.length > 1) {
                        text = arr[1];
                        text = text.substr(0, 4) + '-' + text.substring(4, 6) + '-' + text.substr(-2);
                    } else {
                        text = valid_date.text;
                    }
                    formInfo.idCardInfo = formInfo.idCardInfo || {};
                    formInfo.idCardInfo.idCardValidTime = text || formInfo.idCardInfo.idCardValidTime || '';
                }
                !image_path && this.setData({
                    'ocrFlag.idCardNational': false,
                });
            } else if (subName === 'businessLicenseCopy') {
                const { enterprise_name = {}, reg_num = {}, legal_representative = {} } = e.detail;
                formInfo.bizLicenseInfo = formInfo.bizLicenseInfo || {};
                formInfo.bizLicenseInfo.merchantName = enterprise_name.text || formInfo.bizLicenseInfo.merchantName || '';
                formInfo.bizLicenseInfo.legalPerson = legal_representative.text || formInfo.bizLicenseInfo.legalPerson || '';
                formInfo.bizLicenseInfo.businessLicenseNumber = reg_num.text || formInfo.bizLicenseInfo.businessLicenseNumber || '';
                !image_path && this.setData({
                    'ocrFlag.businessLicenseCopy': false,
                });
            }
            this.setData({ formInfo });
            if (image_path) {
                this._handleUploadMedia(e, image_path);
            } else {
                tipToast('上传失败，请重试');
            }
        },
        handleUploadImage(e) {
            const { file } = e.detail;
            this._handleUploadMedia(e, file ? file.url : '');
        },
        handleChange(e) {
            const { name, subName } = e.currentTarget.dataset;
            const value = e.detail;
            const { formInfo } = this.data;
            if (subName) {
                formInfo[name] = formInfo[name] || {};
                formInfo[name][subName] = value;
            } else {
                formInfo[name] = value;
            }
            this.setData({ formInfo });
        },
        handleShowIdCardValidTime() {
            this.setData({
                'idCardValidTimePopup.show': true,
            });
        },
        handleConfirmIdCardValidTime(e) {
            const { value } = e.detail.value;
            const { formInfo } = this.data;
            if (value === '非长期') {
                this.setData({
                    'idCardValidTimeDatePopup.show': true,
                });
            } else {
                formInfo.idCardInfo.idCardValidTime = value;
                this.setData({ formInfo });
            }
        },
        handleConfirmIdCardValidTimeDate(e) {
            const { formInfo } = this.data;
            formInfo.idCardInfo.idCardValidTime = formatDate(e.detail);
            this.setData({ formInfo });
        },
        handleChangeContactType(e) {
            const { formInfo } = this.data;
            const { value } = e.currentTarget.dataset;
            formInfo.contactInfo.contactType = value;
            this.setData({ formInfo });
        },
        handleDeleteQualification(e) {
            const idx = e.detail.index;
            const { formInfo } = this.data;
            formInfo.qualifications.splice(idx, 1);
            formInfo.qualificationsUrl.splice(idx, 1);
            this.setData({ formInfo });
        },
        handlePrev() {
            this.triggerEvent('prev');
        },
        handleNext() {
            const { merchantShortname, organizationType, idCardInfo, contactInfo, bizLicenseInfo } = this.data.formInfo;
            if (!merchantShortname) {
                tipToast('请输入商户简称');
                return;
            }
            if (organizationType !== WXPAYMENT_ORGANIZATION_TYPE_VALUE.micro) {
                const { businessLicenseCopy, merchantName, legalPerson, businessLicenseNumber } = bizLicenseInfo || {};
                if (!businessLicenseCopy) {
                    tipToast('请上传营业执照图片');
                    return;
                }
                if (!merchantName) {
                    tipToast('请输入商户名称');
                    return;
                }
                if (!legalPerson) {
                    tipToast(`请输入${organizationType === WXPAYMENT_ORGANIZATION_TYPE_VALUE.company ? '法人' : '经营者'}姓名`);
                    return;
                }
                if (!businessLicenseNumber || (businessLicenseNumber.length !== 15 && businessLicenseNumber.length !== 18)) {
                    tipToast('请输入正确的证件注册号');
                    return;
                }
            }
            const { idCardCopy, idCardNational, idCardName, idCardNumber, idCardValidTime } = idCardInfo || {};
            if (!idCardCopy) {
                tipToast('请上传身份证人像面');
                return;
            }
            if (!idCardNational) {
                tipToast('请上传身份证国徽面');
                return;
            }
            if (!idCardName) {
                tipToast('请输入身份证姓名');
                return;
            }
            if (!idCardNumber) {
                tipToast('请输入身份证号');
                return;
            }
            if (!idCardValidTime) {
                tipToast('请输入身份证有效期限');
                return;
            }
            const { contactType, contactName, contactIdCardNumber, mobilePhone, contactEmail } = contactInfo || {};
            if (organizationType !== WXPAYMENT_ORGANIZATION_TYPE_VALUE.micro && contactType === WXPAYMENT_CONTACT_TYPE_VALUE.principal) {
                if (!contactName) {
                    tipToast('请输入超级管理员姓名');
                    return;
                }
                if (!contactIdCardNumber) {
                    tipToast('请输入超级管理员身份证号');
                    return;
                }
            }
            if (!mobilePhone || !isValidPhone(mobilePhone)) {
                tipToast('请输入正确的超级管理员手机号');
                return;
            }
            if (organizationType !== WXPAYMENT_ORGANIZATION_TYPE_VALUE.micro) {
                if (!contactEmail || !isValidMail(contactEmail)) {
                    tipToast('请输入正确的超级管理员邮箱');
                    return;
                }
            } else {
                if (contactEmail && !isValidMail(contactEmail)) {
                    tipToast('请输入正确的超级管理员邮箱');
                    return;
                }
            }

            
            this.triggerEvent('next', this.data.formInfo);
        },
    }
})
